<template>
  <div class="test">
    <!-- video用来开启摄像头 -->
    <video class="input_video" style="display:none"></video>
    <!-- 用来绘制识别内容 -->
    <canvas class="output_canvas" width="1280" height="720"></canvas>
  </div>
</template>

<script>

var hands, video;
export default {
  data() {
    return {
      camera: null,
      canvas: null,
      context: null,
    }
  },
  mounted() {
    this.init();
  },
  beforeUnmount() {
    console.log('Unmount!');
  },
  methods: {
    init() {
      const canvas = document.querySelector('canvas');
      video = document.querySelector('video');
      const context = canvas.getContext('2d');

      hands = new Hands({
        locateFile: (file) => {
          return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;
        }
      });
      hands.setOptions({
        selfieMode: false, //是否自拍，即是否使用前置摄像头
        maxNumHands: 2,  //最大识别手部数量
        minDetectionConfidence: 0.5,  //识别精度，这个数值越高，则要求图像高评分才能被识别 默认 0.5
        minTrackingConfidence: 0.5 //跟踪速度，数值越高，花费时间越长
      });

      async function process() {
        // Draw the overlays.
        context.save();
        // 清空画布
        context.clearRect(0, 0, canvas.width, canvas.height)
        context.drawImage(video, 0, 0, canvas.width, canvas.height)

        await hands.send({ image: video });
        context.restore();

        // context.save();
        // context.restore();
      }

      function onSolved(res) {
        if (res.multiHandLandmarks) {
          for (const landmarks of res.multiHandLandmarks) {
            drawConnectors(context, landmarks, HAND_CONNECTIONS, { color: '#00FF00', lineWidth: 5 });
            drawLandmarks(context, landmarks, { color: '#FF0000', lineWidth: 2 });

            // update fingers state
          }
        }
      }

      hands.onResults(onSolved);

      this.camera = new Camera(video, {
        onFrame: process,
        width: 1280,
        height: 720
      });
      this.camera.start();

    },

  }
}
</script>

<style scoped>
.test {
  width: 1280px;
  height: 720px;
  background: rgb(192, 192, 192);
}
</style>
